package v1

import (
	"bytes"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"sort"

	"github.com/gin-gonic/gin"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/officialaccount/config"
	"github.com/skip2/go-qrcode"

	bc "application/blockchain"
)

// TOKEN 假设您在Go代码中定义了一个名为TOKEN的常量，用于存储您的令牌值
const TOKEN = "2107aaa"

// CheckSignature 配置公众号的token
func CheckSignature(c *gin.Context) {
	signature := c.Query("signature")
	timestamp := c.Query("timestamp")
	nonce := c.Query("nonce")
	echostr := c.Query("echostr")
	token := TOKEN
	strs := sort.StringSlice{token, timestamp, nonce} // 使用本地的token生成校验
	sort.Strings(strs)
	str := ""
	for _, s := range strs {
		str += s
	}
	h := sha1.New()
	h.Write([]byte(str))
	hashcode := fmt.Sprintf("%x", h.Sum(nil))
	if signature == hashcode {
		c.Writer.WriteString(echostr)
	} else {
		c.Writer.WriteString("error")
	}
}
func InitFoundation(c *gin.Context) {
	wc := wechat.NewWechat()
	memory := cache.NewMemory()
	cfg := &config.Config{
		AppID:          "wx2c913f1d499be1cd",
		AppSecret:      "b163040e136d27fc720069e3b2bec334",
		Token:          TOKEN,
		EncodingAESKey: "uxhknC5jxaVuCfWhrRVZg3YSObtFVWcbbU6Q2Lm6Xo6",
		Cache:          memory,
	}
	officialAccount := wc.GetOfficialAccount(cfg)
	token, err := officialAccount.GetAccessToken()
	if err != nil {
		c.JSON(500, gin.H{
			"errcode": 40013,
			"errmsg":  err.Error(),
		})
	}
	c.JSON(200, gin.H{
		"access_token": token,
		"expires_in":   7200,
	})
}
func InitWechatLogin(c *gin.Context) {
	redirectURL := url.QueryEscape("http://915br527pq19.vicp.fun/wechat") //userinfo,
	wechatLoginURL := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&state=%s&scope=snsapi_userinfo#wechat_redirect", "wx2c913f1d499be1cd", redirectURL, "123")
	fmt.Println("wechatLogin", wechatLoginURL)
	wechatLoginURL, _ = url.QueryUnescape(wechatLoginURL)
	// 生成二维码
	qrCode, err := qrcode.Encode(wechatLoginURL, qrcode.Medium, 256)
	if err != nil {
		// 错误处理
		c.String(http.StatusInternalServerError, "Error generating QR code")
		return
	}
	// 将二维码图片作为响应返回给用户
	c.Header("Content-Type", "image/png")
	c.Writer.Write(qrCode)
}

func InitCallBack(c *gin.Context) {
	memory := cache.NewMemory()
	code := c.Query("code")
	cfg := &config.Config{
		AppID:          "wx2c913f1d499be1cd",
		AppSecret:      "b163040e136d27fc720069e3b2bec334",
		Token:          TOKEN,
		EncodingAESKey: "uxhknC5jxaVuCfWhrRVZg3YSObtFVWcbbU6Q2Lm6Xo6",
		Cache:          memory,
	}
	wc := wechat.NewWechat()
	openPlatform := wc.GetOfficialAccount(cfg)
	oAuth := openPlatform.GetOauth()

	if code == "" {
		http.Error(c.Writer, "Missing code parameter", http.StatusBadRequest)
		c.JSON(400, gin.H{
			"msg": "1",
		})
		return
	}

	// 使用code换取access token
	token, err := oAuth.GetUserAccessToken(code)
	if err != nil {
		http.Error(c.Writer, "Failed to get access token: "+err.Error(), http.StatusInternalServerError)
		c.JSON(400, gin.H{
			"msg": "2",
		})
		return
	}

	// 使用access token获取用户信息

	wechatInfo, err := oAuth.GetUserInfo(token.AccessToken, token.OpenID, "")
	if err != nil {
		http.Error(c.Writer, "Failed to get user info: "+err.Error(), http.StatusInternalServerError)
		c.JSON(400, gin.H{
			"msg": "1",
		})
		return
	}
	var bodyByte [][]byte
	bodyByte = append(bodyByte, []byte(wechatInfo.Nickname))
	bodyByte = append(bodyByte, []byte(wechatInfo.OpenID))
	//调用智能合约
	resp, err := bc.ChannelExecute("createMobileUser-key", bodyByte)
	if err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "调用智能合约失败！",
		})
		return
	}
	var data map[string]interface{}
	err = json.Unmarshal(bytes.NewBuffer(resp.Payload).Bytes(), &data)
	if err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "反序列化失败！",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "登录成功",
	})
}
